<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\User;
use App\Model\Role;
use App\Model\Account;
use App\Http\Resources\UserResource;
use App\Http\Resources\UserCollection;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Http\Requests\UserRequest;
use Ramsey\Uuid\Uuid;
use App\Model\Score;
class ScoreController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function home(Request $request)
    {
		$data['code']=0;
		$data['data']=Score::paginate(12);
		$data['error']="";
		$data['msg']="success";
		$data['timestamp']=time();
		return $data;
    }
	
    public function export(Request $request)
    {
		$data['code']=0;
		$data['data']=User::paginate(12);
		$data['error']="";
		$data['msg']="success";
		$data['timestamp']=time();
		return $data;
    }
	
	public function import(Request $request)
    {
		foreach($request->all() as $item){
		  Score::create($item);
		}
		$data['code']=0;
		$data['data']='';
		$data['error']="";
		$data['msg']="success";
		$data['timestamp']=time();
		return $data;
    }
	
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(UserRequest $request)
    {
		$data=[
			'name' => $request->name,
			'passed' => $request->passed,
			'avatar' => $request->avatar,
			'nickname' => $request->nickname,
			'phone' => $request->phone,
			'email' => $request->email,
			'role_id' => $request->role_id,
			'role_name' => $request->role_name,
			'desc' => $request->desc				
		];
				
		if($data['role_id']==-1){
			$data['role_name']='内置角色';
		}elseif($role=Role::where('id',$data['role_id'])->first()){
			$data['role_name']=$role->name;
		}else{
			$data['role_id']=0;
			$data['role_name']='';
		}
		
		$request->password?$data['password']=Hash::make($request->password):'';

	   if($user=User::where("id",$request->id)->update($data)){
		   return ['code'=>0,"data"=>[],'msg'=>'修改成功'];
	   }	  
			
	   if(!$request->id&&!User::where("name",$request->name)->first()){
			User::create($data);
			return ['code'=>0,"data"=>[],'msg'=>'创建成功'];
	   }
	   
	   return ['code'=>101,"data"=>[],'msg'=>'帐号已存在'];
    }

    public function show(Request $request,$id)
    {
		return new UserResource(User::where("id",$id)->first());
       
	}
	
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function delete(Request $request)
    {
		if($request->user('api')->id==$request->id){
			return ['code'=>0,"data"=>0,'msg'=>'删除失败,你没有权限删除此用户'];
		}
		
		if(User::where("id",$request->id)->where("is_system",'<>',1)->delete()){
          return ['code'=>0,"data"=>1,'msg'=>'删除成功'];
		}else{
          return ['code'=>0,"data"=>0,'msg'=>'删除失败,你没有权限删除此用户'];
		}
    }
}
